package motionsApp.client.labeling;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import motionsApp.client.MotionsChangedCallback;
import motionsApp.client.MotionsRepository;
import motionsApp.shared.MotionDTO;

import com.google.gwt.user.client.ui.HasWidgets;

public class MotionLabeler implements MotionsChangedCallback, LabelAddedCallback {
	private static final Random RANDOM = new Random();
	private MotionsRepository repository;
	private MotionToLabelPainter painter;
	private List<MotionDTO> motions;
	private MotionDTO currentMotion;

	public MotionLabeler(MotionsRepository repository, HasWidgets panel){
		this.repository = repository;		
		painter = new MotionToLabelPainter(panel, this);
		motions = new ArrayList<MotionDTO>();
		repository.registerListener(this);		
	}

	@Override
	public void onChange(List<MotionDTO> motions) {
		this.motions = motions;		
		
		setNewMotion();
		
		Set<String> availabeLabels = new HashSet<String>();
		for (MotionDTO motion : this.motions) {
			for (String label : motion.getLabels()) {
				availabeLabels.add(label);
			}
		}		
	}

	private void setNewMotion() {
		if(this.motions.size() == 0){
			painter.setMotion("System has no motions", null);			
			return;
		}
		
		final int nextMotionIndex = RANDOM.nextInt(this.motions.size());
		currentMotion = this.motions.get(nextMotionIndex);
		painter.setMotion(currentMotion.getName(), currentMotion.getLabels());
	}

	@Override
	public void labelAdded(String label) {
		HashSet<String> newLabels = new HashSet<String>();
		newLabels.addAll(currentMotion.getLabels());
		newLabels.add(label);
		repository.UpdateMotionLabels(currentMotion, newLabels);		
	}

	@Override
	public void newMotionRequested() {
		setNewMotion();		
	}
}
